package jh.com.jhappbf.dispatchcar;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;

import com.ab.activity.AbActivity;
import com.ab.fragment.AbDialogFragment;
import com.ab.util.AbDialogUtil;
import com.ab.util.AbToastUtil;
import com.ab.view.pullview.AbPullToRefreshView;
import com.ab.view.titlebar.AbTitleBar;
import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import jh.com.jhappbf.R;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.model.DanhaoModel;
import jh.com.jhappbf.model.PihaoModel;
import jh.com.jhappbf.ui.State;
import jh.com.jhappbf.utils.JsonHelper;

/**
 * @author Administrator
 */
public class ContractSelect extends AbActivity{
    private View mNetErrorView;
    private View mDataContentView;
    private AbPullToRefreshView mRefreshView;
    private ListView mListView;
    private Button mTryAgain;
    private Context mAppContext;
    private ArrayList<DanhaoModel> danhaoModels;

    private MyBaseAdapter mAdapter;
    private AbDialogFragment mDialogFragment;
    private String dispatchId;
    private String plateNum;
    private String saverFactory;
    private String flag;
    private String mType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDataContentView = View.inflate(ContractSelect.this, R.layout.dispatch_car_query_activity, null);
        mNetErrorView = View.inflate(ContractSelect.this, R.layout.net_error_activity, null);
        setAbContentView(mDataContentView);
        AbTitleBar mAbTitleBar = this.getTitleBar();
        dispatchId=getIntent().getStringExtra("dispatchId");
        plateNum=getIntent().getStringExtra("plateNum");
        saverFactory=getIntent().getStringExtra("saverFactory");
        flag=getIntent().getStringExtra("flag");
        mType=getIntent().getStringExtra("mType");
        mAbTitleBar.setTitleText("选择单号");
        mAbTitleBar.setLogo(R.drawable.button_selector_back);
        mAbTitleBar.setTitleBarBackgroundColor(ContextCompat.getColor(this, R.color.orange));
        mAbTitleBar.setTitleTextMargin(10, 0, 0, 0);
        mAbTitleBar.setLogoLine(R.mipmap.line);
        mAbTitleBar.setLogoOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        View rightViewMore = mInflater.inflate(R.layout.title_right_ok_btn_view, null);
        mAbTitleBar.addRightView(rightViewMore);
        Button mTitleRightBtn = rightViewMore.findViewById(R.id.title_right_ok_btn);
        mTitleRightBtn.setOnClickListener(v -> {
            confirmSelect();
        });
        initView();
    }
    /**
     * 保存
     */
    private void confirmSelect() {
        if (!TextUtils.equals("采购",mType)){
            if (TextUtils.isEmpty(flag)){
                boolean isExiet=false;
                for (DanhaoModel danhaomodel:danhaoModels) {
                    if (danhaomodel.isIscheck()){
                        if (isExiet){
                            AbToastUtil.showToast(this,"只能确认一个交货行号！");
                            return;
                        }
                        isExiet=true;
                    }
                }
            }
            else {
                for (DanhaoModel danhaomodel:danhaoModels) {
                    if (danhaomodel.isIscheck()){
                        String danhao=danhaomodel.getBy8();
                        for (DanhaoModel danhaomodel2:danhaoModels) {
                            if (danhao.equals(danhaomodel2.getBy8())&&!danhaomodel2.isIscheck()){
                                AbToastUtil.showToast(this,"该交货单还有单号未提交！");
                                return;
                            }
                        }
                    }
                }
            }

        }
        Intent i = new Intent();
        i.putExtra("danhaoModels",danhaoModels);
        setResult(3, i);
        this.finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * 初始化界面
     */
    private int currentEditPosition  = -1;
    private void initView() {
        mListView = mDataContentView.findViewById(R.id.dispatch_query_listView);
        mListView = mDataContentView.findViewById(R.id.dispatch_query_listView);
        mRefreshView = mDataContentView.findViewById(R.id.dispatch_query_pullToRefreshView);
        mTryAgain = mNetErrorView.findViewById(R.id.network_error_btn);
        mAppContext = getApplicationContext();
        danhaoModels = new ArrayList<>();

        mAdapter = new MyBaseAdapter();
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener((parent, view, position, id) -> {
            currentEditPosition=position;
            if (TextUtils.isEmpty(flag)&&!TextUtils.equals(danhaoModels.get(position).getBy22(),"TO")){
                AbToastUtil.showToast(this,"不允许非定额确认");
                return;
            }
            Intent intent=null;
            if (TextUtils.equals(danhaoModels.get(position).getBy4(),"BOTH")&&TextUtils.equals("交货",mType)){
                if (TextUtils.equals(danhaoModels.get(position).getBy25(),saverFactory)){
                    danhaoModels.get(position).setBy4("IN");
                }else {
                    danhaoModels.get(position).setBy4("OUT");
                }
            }
            if (TextUtils.equals(danhaoModels.get(position).getBy4(),"IN")){
                intent= new Intent(this, ContractSelectPihao.class);
            }
            else
            {
                if (TextUtils.equals("交货",mType)){
                    intent= new Intent(this, ContractSelectPihaoSale.class);
                }else  if (TextUtils.equals("采购",mType)){
                    intent= new Intent(this, ContractSelectPihaoBuy.class);
                }else {
                    intent= new Intent(this, ContractSelectPihaoYuLiu.class);
                }
            }
            intent.putExtra("CompanyCode",saverFactory);
            intent.putExtra("cargonameId",danhaoModels.get(position).getBy21());
            intent.putExtra("danhao",danhaoModels.get(position).getBy8());
            intent.putExtra("hanghao",danhaoModels.get(position).getBy9());
            intent.putExtra("danwei",danhaoModels.get(position).getBy22());
            intent.putExtra("initGross",danhaoModels.get(position).getInitGross()+"");//订单数量
            intent.putExtra("mType",danhaoModels.get(position).getType()+"");//订单类型
            intent.putExtra("flag",flag);
            intent.putExtra("PihaoModels",danhaoModels.get(position).getPihaoModels());
            startActivityForResult(intent, 10086);
        });

        mTryAgain.setOnClickListener(v -> {
            setAbContentView(mDataContentView);
            loadFirst();
        });
        mRefreshView.setOnHeaderRefreshListener(view -> refreshTask());
        mRefreshView.setOnFooterLoadListener(view -> mRefreshView.onHeaderRefreshFinish());

        loadFirst();
    }

    /**
     * 第一次加载
     */
    private void loadFirst() {
        mDialogFragment = AbDialogUtil.showLoadDialog(this, R.mipmap.ic_load,
                "查询中,请稍等...");
        mDialogFragment.setCancelable(false);
        mDialogFragment.setAbDialogOnLoadListener(this::refreshTask);
    }

    /**
     * 上拉刷新
     */
    private void refreshTask() {
        String methodName = "queryUnloadDispatch";
        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        param.add("id");
        param.add("plate");
        param.add("company");
        value.add(dispatchId);
        value.add(plateNum);
        value.add(State.mCompanyName);

        Listener<String> listener = response -> {
            AbDialogUtil.removeDialog(ContractSelect.this);
            mRefreshView.onHeaderRefreshFinish();
            List<JSONObject> data = JsonHelper.getJsonObjects(response);
            danhaoModels= JsonHelper.getEntityFromJsonDanhaoModel(response,DanhaoModel.class);
            if (TextUtils.isEmpty(flag)&&TextUtils.equals("交货",mType)&&danhaoModels.size()>1){
                AbToastUtil.showToast(this,"多行号不能非定额确认！");
                this.finish();
            }
            if (danhaoModels != null) {
                mAdapter.notifyDataSetChanged();
            }
        };

        ErrorListener errorListener = error -> {
            AbDialogUtil.removeDialog(ContractSelect.this);
            mRefreshView.onHeaderRefreshFinish();
            setAbContentView(mNetErrorView);
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(getApplicationContext()).addRequest(
                webService);
    }

    class MyBaseAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return danhaoModels!=null?danhaoModels.size():0;
        }

        @Override
        public Object getItem(int position) {
            return danhaoModels.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final int index=position;
            ViewHolder holder;
            if (convertView == null) {
                convertView = View.inflate(ContractSelect.this,R.layout.list_view_item_txt_check, null);
                holder = new ViewHolder();
                holder.txt = convertView.findViewById(R.id.list_view_item_txt);
                holder.ckx=convertView.findViewById(R.id.list_view_item_check);
                convertView.setTag(holder);
                holder.ckx.setTag(index);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            String symbol = "\r\n";
            DanhaoModel danhaoModel = danhaoModels.get(position);
            StringBuilder builder=new StringBuilder();
            String ids=danhaoModel.getID();
            builder.append("单号："+ danhaoModel.getBy8());
            builder.append(symbol);
            builder.append("行号："+ danhaoModel.getBy9());
            builder.append(symbol);
            builder.append("物料编码："+ danhaoModel.getBy21().substring(10));
            builder.append(symbol);
            builder.append("物料名："+ danhaoModel.getCargoname());
            builder.append(symbol);
            builder.append("工厂代码："+ danhaoModel.getCompanyCode());
            holder.txt.setText(builder);
            if (danhaoModel.isIscheck()){
                holder.ckx.setChecked(true);
            }else {
                holder.ckx.setChecked(false);
            }
            return convertView;
        }
    }

    class ViewHolder {
        public TextView txt;
        public CheckBox ckx;
    }

    @Override
    public void onBackPressed() {
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data!=null){
            switch (requestCode){
                case 10086:
                    ArrayList<PihaoModel> pihaoModels = (ArrayList<PihaoModel>) data.getSerializableExtra("pihaoModels");
                    danhaoModels.get(currentEditPosition).setPihaoModels(pihaoModels);
                    boolean ischeck=false;
                    for (PihaoModel pihaoModel:pihaoModels){
                        if (pihaoModel.isChk()){
                            ischeck=true;
                        }
                    }
                    if (ischeck){
                        danhaoModels.get(currentEditPosition).setIscheck(true);
                    }else {
                        danhaoModels.get(currentEditPosition).setIscheck(false);
                    }
                    mAdapter.notifyDataSetChanged();
                    break;
            }
        }
    }
}
